<template>
  <div ref="chart" class="bar-chart"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';
import titleIcon from '@/assets/images/titleIcon.png';

const props = defineProps({
  // 传入的数据，格式如下：[{ name: '类别1', value: 120 }, { name: '类别2', value: 200 }]
  data: {
    type: Object,
  },
  // 图表标题
  title: {
    type: String,
    default: '',
  },
  // X轴的标题
  xAxisLabel: {
    type: String,
    default: '',
  },
  // Y轴的标题
  yAxisLabel: {
    type: String,
    default: '',
  },
  xLabel: {
    type: Array,
    default: () => []
  },
  index: {
    type: Number,
    default: 3
  },
});
function getGradientColor(index: number): echarts.graphic.LinearGradient {
  let startColor: string;
  let endColor: string;

  switch (index) {
    case 1:
      startColor = '#55B68B';
      endColor = '#4EA775';
      break;
    case 0:
      startColor = '#3560F6';
      endColor = '#69D0FF';
      break;
    case 2:
      startColor = '#FA880E';
      endColor = '#F4BA43';
      break;
  }

  return new echarts.graphic.LinearGradient(
    0, 0, 0, 1, // 渐变方向，从上到下
    [
      { offset: 0, color: startColor }, // 起始颜色
      { offset: 1, color: endColor }  // 结束颜色
    ]
  );
}
const chart = ref(null);
let myChart = null;

onMounted(() => {
  // 初始化图表
  myChart = echarts.init(chart.value);

  // 渲染图表
  updateChart();

  window.addEventListener('resize', resizeChart);
});

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose();
  }
  window.removeEventListener('resize', resizeChart);
});

watch(() => props.data, () => {
  // 数据变化时更新图表
  updateChart();
}, { deep: true });
watch(() => props.xLabel, () => {
  // 数据变化时更新图表
  updateChart();
}, { deep: true });
function updateChart() {
  if (!myChart) return;
  let data = [
    {
      type: 'bar',
      barMaxWidth: 20,
      data: props.data.dieDataYear,
      name: '死亡',
      barBorderRadius: [2, 2, 0, 0],
      itemStyle: {
        color: getGradientColor(0),
        borderRadius: [2, 2, 0, 0],
      },
      emphasis: {
        itemStyle: {
          borderRadius: [2, 2, 0, 0] // 确保在强调状态下也生效
        }
      },
      index: 0,
      label: {
        show: true,
        position: 'top', // 将标签显示在柱状图的正上方
        rich: {
          color0: {color: '#3B68F7'}// 定义颜色样式
        },
        formatter: (params) => {
          if(params.value === 0){
            return '';
          }else {
            return `{color0|${params.value}}`;
          }
        }
      }
    },
    {
      type: 'bar',
      barMaxWidth: 20,
      data: props.data.disappearDataYear,
      name: '失踪',
      barBorderRadius: [2, 2, 0, 0],
      itemStyle: {
        color: getGradientColor(1),
        borderRadius: [2, 2, 0, 0],
      },
      emphasis: {
        itemStyle: {
          borderRadius: [2, 2, 0, 0] // 确保在强调状态下也生效
        }
      },
      index: 1,
      label: {
        show: true,
        position: 'top', // 将标签显示在柱状图的正上方
        rich: {
          color0: {color: '#55B080'}// 定义颜色样式
        },
        formatter: (params) => {
          if(params.value === 0){
            return '';
          }else {
            return `{color0|${params.value}}`;
          }
        }
      }
    },
    {
      type: 'bar',
      barMaxWidth: 20,
      data: props.data.injuredDataYear,
      name: '受伤',
      barBorderRadius: [2, 2, 0, 0],
      itemStyle: {
        color: getGradientColor(0),
        borderRadius: [2, 2, 0, 0],
      },
      emphasis: {
        itemStyle: {
          borderRadius: [2, 2, 0, 0] // 确保在强调状态下也生效
        }
      },
      index: 0,
      label: {
        show: true,
        position: 'top', // 将标签显示在柱状图的正上方
        rich: {
          color0: {color: '#3B68F7'}// 定义颜色样式
        },
        formatter: (params) => {
          if(params.value === 0){
            return '';
          }else {
            return `{color0|${params.value}}`;
          }
        }
      }
    },
    {
      type: 'bar',
      barMaxWidth: 20,
      data: props.data.economicsYear,
      name: '经济损失',
      barBorderRadius: [2, 2, 0, 0],
      itemStyle: {
        color: getGradientColor(2),
        borderRadius: [2, 2, 0, 0],
      },
      emphasis: {
        itemStyle: {
          borderRadius: [2, 2, 0, 0] // 确保在强调状态下也生效
        }
      },
      index: 2,
      label: {
        show: true,
        position: 'top', // 将标签显示在柱状图的正上方
        rich: {
          color0: {color: '#FA8C12'}// 定义颜色样式
        },
        formatter: (params) => {
          if(params.value === 0){
            return '';
          }else {
            return `{color0|${params.value}}`;
          }
        }
      }
    },
  ].slice(props.index == 1 ? 0 : props.index, props.index + 1)
  const option = {
    title: {
      text: `{icon|}{text|${props.title}}`,
      textStyle: {
        rich: {
          icon: {
            backgroundColor: {
              image: titleIcon
            },
            width: 16,
            height: 16,
            align: 'center',
            verticalAlign: 'middle'
          },
          text: {
            color: '#333',
            fontSize: 16,
            align: 'left',
            verticalAlign: 'middle',
            padding: [0, 0, 0, 4]
          }
        }
      },
      left: 'left',
      top: 'top'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '2%',
      containLabel: true
    },
    legend: {
      data: data.map((dataset) => ({
        name: dataset.name,
        textStyle: {
          color: '#333333' // 默认黑色文字
        },
        itemStyle: {
          color: getGradientColor(dataset.index), // 图例颜色
        },
        icon: 'roundRect',
        symbolSize: 10,
      })),
      top: '5%',
      left: 'center'
    },
    xAxis: {
      type: 'category',
      data: props.data.yearData,
      axisTick: {
        show: false
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#D9E1F3', // 设置 x 轴线的颜色
          width: 1 // 设置 x 轴线的宽度
        }
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#999999',
          fsize: 12
        }
      }
    },
    yAxis: {
      type: 'value',
      name: props.yAxisLabel,
      nameTextStyle:{
        color: '#86909C'
      },
      minInterval: 1,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#D9E1F3',
        }
      },
      max: null ,
      axisTick: {
        show: false
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#D9E1F3', // 设置 x 轴线的颜色
          width: 1 // 设置 x 轴线的宽度
        }
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: '#999999',
          fsize: 12
        }
      }
    },
    series: data,
  };

  // 使用 setOption 更新图表数据
  myChart.setOption(option);
}

function resizeChart() {
  if (myChart) {
    myChart.resize();
  }
}
</script>

<style scoped>
.bar-chart {
  width: 100%;
  height: 400px;
}
</style>